import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {ElectronService} from 'ngx-electron';
import {AppService} from '../../service/app/app.service';
import {DataServerService} from '../../service/data-server';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-charge',
  templateUrl: './charge.component.html',
  styleUrls: ['./charge.component.css']
})
export class ChargeComponent implements OnInit {
  airpay = true;
  weixin = false;
  money = 0;
  backRouter = 'user';
  validateForm: FormGroup;
  chargeImg = require('../../../assets/charge.png');
  constructor(private fb: FormBuilder,
              private dataServce: DataServerService,
              private appService: AppService,
              private message: NzMessageService,
              private electron: ElectronService,
              private router: Router) {
    this.validateForm = this.fb.group({
      money: ['', [Validators.required]],
    });
  }

  ngOnInit() {
    if (this.dataServce.data !== null && this.dataServce.data !== undefined) {
      if (this.dataServce.data.hasOwnProperty('money') && this.dataServce.data['money'] > 0) {
        this.money = this.dataServce.data['money'];
      }
      if (this.dataServce.data.hasOwnProperty('router') && this.dataServce.data['router'] !== 'user') {
        this.backRouter = this.dataServce.data['router'];
      }
    }
    this.validateForm.patchValue({'money': this.money});
  }
  chooseAirpay() {
    this.airpay = true;
    this.weixin = false;
  }
  chooseWeixinpay() {
    this.airpay = false;
    this.weixin = true;
  }
  charge() {
    console.log(this.validateForm.valid);
    if (this.validateForm.valid) {
      console.log(this.validateForm.value);
      let type;
      if (this.airpay) {
        type = 'alipay';
      } else {
        type = 'wxpay';
      }
      this.appService.post(this.appService.urls.recharge + localStorage.getItem('user_id') + '?access_token=' + localStorage.getItem('token'),
          {'type': type, 'price': this.validateForm.value.money}).subscribe((resp: any) => {
        if (resp.body.ret === 1) {
          if (this.electron.isElectronApp) {
            this.electron.ipcRenderer.send('charge', resp.body.data.url);
          } else {
            android.charge(resp.body.data.url);
          }
        } else {
          this.message.error('充值失败！');
        }
      });
    }
  }
  backToUser() {
    this.dataServce.data = null;
    this.router.navigate([this.backRouter]).catch();
  }
}
